package org.jcms.service.impl;

import java.util.List;

import org.jcms.model.Book;
import org.jcms.model.Manager;
import org.jcms.model.Order;
import org.jcms.model.OrderBook;
import org.jcms.model.Proof;
import org.jcms.service.ManagerServiceI;
import org.jcms.service.OrderBookServiceI;
import org.jcms.service.base.GenericDaoImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class ManagerServiceImpl extends GenericDaoImpl<Manager> implements
		ManagerServiceI {

	@Override
	public void payAndBuildProof(Order order, Proof proof,
			OrderBookServiceI orderBookServiceI) {
		org.hibernate.classic.Session session = sessionFactory
				.getCurrentSession();

		session.update(order);

		session.save(proof);

		List<OrderBook> orderBookls = orderBookServiceI
				.findByHQL("from OrderBook where id.order.orderId = ?",
						order.getOrderId());

		for (OrderBook orderBook : orderBookls) {
			Book book = (Book) session.get(Book.class, orderBook.getId()
					.getBook().getBookIsbn());
			book.setBookOrderNumber(book.getBookOrderNumber()
					+ orderBook.getOrderBookNumber());
			// session.update(book);
			/*
			 * orderBook .getId() .getBook() .setBookOrderNumber(
			 * orderBook.getId().getBook().getBookOrderNumber() +
			 * orderBook.getOrderBookNumber());
			 * session.update(orderBook.getId().getBook());
			 */
		}
	}

	@Override
	public void sellBook(Order order, Proof proof,
			OrderBookServiceI orderBookServiceI) {
		org.hibernate.classic.Session session = sessionFactory
				.getCurrentSession();

		session.update(order);

		session.update(proof);

		List<OrderBook> orderBookls = orderBookServiceI
				.findByHQL("from OrderBook where id.order.orderId = ?",
						order.getOrderId());

		for (OrderBook orderBook : orderBookls) {
			Book book = (Book) session.get(Book.class, orderBook.getId()
					.getBook().getBookIsbn());
			int bookStock = book.getBookStock();
			int orderBookNumberorder = orderBook.getOrderBookNumber();
			if (bookStock < orderBookNumberorder) {
				throw new RuntimeException(book.getBookIsbn());
			}
			book.setBookOrderNumber(book.getBookOrderNumber()
					- orderBookNumberorder);
			book.setBookStock(bookStock - orderBookNumberorder);

		}

	}

}
